/*

Author : 
	aziza yasser: 15898607 : ICB5
	sayli hidir: 06061308 : IFS 4
*/

#include "MTF.h"
#define BYTE 256


std::string MTF::Decode(std::string filename)
{
	std::fstream input;
	unsigned char alphabet[BYTE];
	for(int i=0;i<BYTE;i++)
		alphabet[i]=i;

	input.open(filename.c_str(),std::ios::in | std::ios::binary);
	std::fstream out;
	out.open((filename+"-MTF.dec").c_str(),std::ios::out | std::ios::binary);
	while(input)
	{
		int tmp=input.get();
		if(!input) break;
		out << (char)alphabet[tmp];
		int reverse=tmp;
		tmp=alphabet[tmp];
		for(;reverse>0;reverse--)
			alphabet[reverse]=alphabet[reverse-1];
		alphabet[0]=(char)tmp;
	}
	input.close();
	out.close();
	std::cout<< filename << "-MTF.dec \n";
	return (filename+"-MTF.dec");
}


std::string MTF::Encode(std::string filename)
{
	std::fstream file;				//Prep Source File
	unsigned char alphabet[BYTE];	//Prep Alphabet
	for(int i=0;i<BYTE;i++)			//Load Alphabet
		alphabet[i]=i;


	file.open(filename.c_str(), std::ios::in |std::ios::binary);	//Open Source File
	std::fstream out;
	out.open((filename+"-MTF.enc").c_str(),std::ios::out|std::ios::binary);
	while(file)	//Read from file as long as eof!=0
	{
		int bin=file.get(); //get next input from file
		int forward=0;
		for(;forward<BYTE;forward++)
		{
			if(alphabet[forward]==bin)
			{
				for(int reverse=forward;reverse>0;reverse--) //MTF algorithm
					alphabet[reverse]=alphabet[reverse-1];
				alphabet[0]=bin;
				break;
			}
		}
		if(file)
			out << (char)forward;
	}
	file.close();
	out.close();
		
	std::cout<< filename << "-MTF.enc \n";
	return (filename+"-MTF.enc");
}